<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px; margin-right: 5px;" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
      <el-input clearable @clear="load" style="width: 260px; margin-right: 5px;" v-model="data.username" placeholder="请输入账号查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button type="info" @click="reset">重 置</el-button>

    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="headleAdd">新   增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      <el-button type="info" @click="exportData">批量导出</el-button>
      <el-upload
          style="display: inline-block; margin-left: 10px"
        action="http://localhost:9999/user/import"
        :show-file-list="false"
        :on-success="handleImportSuccess"
      >
        <el-button type="success">批量导入</el-button>
      </el-upload>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table @selection-change="handleSelectionChange" :data="data.tableData" style="width: 100%" :header-cell-style="{ color:'#333',backgroundColor:'#dde8ff'}">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="头像" width="100">
          <template #default="scope">
            <el-image :preview-src-list="[scope.row.avatar]" :preview-teleported="true" v-if="scope.row.avatar" :src="scope.row.avatar" alt="" style="width: 40px; height: 40px; display: block; border-radius: 50%"/>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="primary" icon="Edit" circle @click="headleEdit(scope.row)" ></el-button>
            <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)" ></el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="care">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 15]"
          :total="data.total"
          @current-change="load"
          @size-change="load"
      />
    </div>
    <el-dialog v-model="data.formVisible" title="普通用户信息" destroy-on-close width="30%">
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="username" label="账号" >
          <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item prop="name" label="名称" >
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item prop="phone" label="电话" >
          <el-input v-model="data.form.phone" autocomplete="off" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" >
          <el-input v-model="data.form.email" autocomplete="off" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item prop="avatar" label="头像" >
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{token: data.user.token}"
              :on-success="handleFileSuccess"
              list-type="picture"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
//  数据定义
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  name:'',
  username:'',
  pageNum: 1,
  pageSize: 5,
  total: 6,
  tableData:[],
  formVisible: false,
  form:{},
  rows:[],
  ids:[],
  rules:{
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入电话', trigger: 'blur' },
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' }
    ],
  }
})
const formRef = ref()
// 数据获取查询按钮
const load = () =>{
  request.get('user/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name: data.name,
      username: data.username
    }
  }).then(res =>{
    if(res.code === '200'){
      data.tableData =res.data.list
      data.total = res.data.total
    }else {
      ElMessage.error(res.msg)
    }
  })
}
load()
// 重置按钮
const reset = () =>{
  data.name = ''
  data.username = ''
  load()
}
// 新增按钮
const headleAdd = () =>{
  data.form = {}
  data.formVisible = true
}
// 新增保存按钮
const add = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if(!valid){
      return false
    }
    console.log(data.form)
    request.post('user/add',data.form).then(res =>{
      if(res.code === '200'){
        data.formVisible = false
        ElMessage.success('新增成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  })
}
// 修改保存按钮
const headleEdit = (row) =>{
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}
// 修改编辑按钮
const update = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if(!valid){
      return false
    }
    request.put('user/update',data.form).then(res =>{
      if(res.code === '200'){
        data.formVisible = false
        ElMessage.success('修改成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  })
}
//  保存按钮 判断是新增还是修改
const save = () =>{
  if(data.form.id){
    console.log(data.form)
    update()
  }else {
    // add()
  }
}
// 删除按钮
const del = (id) =>{
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '删除确认', {type: 'warning',}).then(res => {
    console.log(id)
    request.delete('/user/delete/'+id).then(res =>{
      if(res.code === '200'){
        ElMessage.success('删除成功')
        load()
      }
    }).catch(() => {
      ElMessage.error(res.msg)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  });
}
//  多选
const handleSelectionChange = (rows) => {
  console.log(rows)
  data.rows = rows
  data.ids = data.rows.map(item => item.id)
}
//  批量删除
const deleteBatch =  () =>{
  console.log(data.rows)
  if(data.rows.length === 0){
    console.log(data.rows)
    ElMessage.warning('请选择要删除的行')
    return
  }
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '删除确认', {type: 'warning',}).then(res => {
    request.delete('/user/deleteBatch',{data:data.rows}).then(res =>{
      if(res.code === '200'){
        ElMessage.success('批量删除成功')
        load()
      }
    }).catch(() => {
      ElMessage.error(res.msg)
    })
  }).catch(() => {
    ElMessage.info('已取消批量删除')
  });
}

const exportData = () => {
  let idsStr = data.ids.join(',') // 将数组转换为字符串
  let url = `http://localhost:9999/user/export?username=${data.username}&name=${data.name}`
  + `&ids=${idsStr}` + `&token=${data.user.token}`
  window.open(url)

}

const handleImportSuccess = (res) => {
  if(res.code === '200'){
    ElMessage.success('上传成功')
    load()
  }else {
    ElMessage.error(res.msg)
  }
}

const handleFileSuccess = (res) => {
  data.form.avatar = res.data
}
</script>
